'use strict'

var log4js = require('log4js');
var http = require('http');
var https = require('https');
var fs = require('fs');

var socketIo = require('socket.io');
var express = require('express');
var serveIndex = require('serve-index');

var USERCOUNT = 3;

log4js.configure({
    appenders:{
        file:{
            type:'file',
            filename:'app.log',
            layout:{
                type:'pattern',
                pattern:'%r %p - %m',
            }
        }
    },
    categories:{
        default:{
            appenders:['file'],
            level:'debug'
        }
    }
});

var logger = log4js.getLogger();

var app = express();
app.use(serveIndex('./public'));
app.use(express.static('./public'));

app.all("*",function(req,res,next){
    res.header("Access-Control-Allow-Origin","*");

    res.header("Access-Control-Allow-Headers","content-type");

    res.header("Access-Control-Allow-Methods","DELETE,PUT,POST,GET,OPTTONS");

    if(req.method.toLowerCase() == 'options'){
        res.send(200);
    }else{
        next();
    }
});

var http_server = http.createServer(app);
http_server.listen(80,'0.0.0.0');

var options = {
    key : fs.readFileSync('./cert/cert.key'),
    cert : fs.readFileSync('./cert/cert.pem')
}

var https_server = https.createServer(options , app);
var io = socketIo.listen(https_server);

io.sockets.on('connection' ,(socket)=>{
    
    socket.on('message' , (room,data)=>{
        logger.debug('message, room: ' + room + ", data, type:" + data.type);
        socket.to(room).emit('message', room , data);
    });
    //socket.emit() - 发送给自己​
    //socket.to(room).emit() - 发送给房间内的其他人​

    socket.on('join' , (room)=>{
        socket.join(room);

        var myRoom = io.sockets.adapter.rooms[room];
        var users = (myRoom)?Object.keys(myRoom.sockets).length : 0;
        
        logger.debug('the user number of room (' + room + ') is: ' + users);

        if(users < USERCOUNT){
            socket.emit('joined' , room ,socket.id);

            if(users > 1)
            {
                socket.to(room).emit('other_join' , room ,socket.id);
            }

        }else{
            socket.leave(room);
            socket.emit('full', room ,socket.id);
        }

    });

    socket.on('leave' , (room)=>{
        socket.leave(room);
        var myRoom = io.sockets.adapter.rooms[room];
        var users = (myRoom) ? Object.keys(myRoom.sockets).length : 0;
        logger.debug('the user number of room is: ' + users);

        socket.to(room).emit('bye' , room , socket.id);


        socket.emit('left' , room, socket.id);
    });


});

https_server.listen(443, '0.0.0.0');
